package com.test.controller;

import com.test.entity.LoginParam;
import com.test.entity.ResultEntity;
import com.test.entity.pojo.UserEntity;
import com.test.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

/**
 * Author: admin
 * Date: 2022/11/17 9:29
 * Describe: TODO
 */
@RestController
@RequestMapping("/API")
public class LoginController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private IUserService userService;

    @PostMapping("/register")
    public ResultEntity register(@RequestBody LoginParam param) {
        UserEntity user = new UserEntity();
        // 调用加密器将前端传递过来的密码进行加密
        user.setUsername(param.getUsername());
        user.setPassword(passwordEncoder.encode(param.getPassword()));
        // 将用户实体对象添加到数据库
        userService.save(user);
        return new ResultEntity(0, "操作成功", "注册成功");
    }

    @PostMapping("/login")
    public ResultEntity login(@RequestBody LoginParam param) {
        /** 集成 JWT 之前的代码, 基于session的方式认证，当登录成功之后，立刻调用其他接口也会成功，比如 /book/test1接口
        // 生成一个包含账号密码的认证信息
        Authentication token = new UsernamePasswordAuthenticationToken(param.getUsername(), param.getPassword());
        // AuthenticationManager校验这个认证信息，返回一个已认证的Authentication
        Authentication authentication = authenticationManager.authenticate(token);
        // 将返回的Authentication存到上下文中
        SecurityContextHolder.getContext().setAuthentication(authentication);
        return new ResultEntity(0, "操作成功", "登录成功");
         */
        return userService.login(param);
    }

    @GetMapping("/logout")
    public String logout() {
        SecurityContextHolder.clearContext();
        return "退出成功";
    }

}
